package com.xbongbong.paas.service.workflow.setting.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.config.enums.WorkflowTriggerMethodEnum;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.workflow.NodeCoreConfigurationPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowNodeTreePojo;
import com.xbongbong.paas.pojo.workflow.nodes.vo.InsertRecordNodeVO;
import com.xbongbong.paas.pojo.workflow.nodes.vo.WorkflowNodeGetVO;
import com.xbongbong.paas.pojo.workflow.settings.WorkflowGetPojo;
import com.xbongbong.paas.pojo.workflow.settings.vo.WorkflowEnableVO;
import com.xbongbong.paas.pojo.workflow.settings.vo.WorkflowOperationsVO;
import com.xbongbong.paas.service.workflow.setting.AbstractWorkflowNodeSettings;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.WorkflowNodeUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.domain.entity.ext.WorkflowNodeEntityExt;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.pojo.nodes.InsertRecordNode;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2021/05/21 14:35
 */
@Service("workflowNodeInsertSettings")
public class WorkflowNodeCreateSettings extends AbstractWorkflowNodeSettings {

    private static String CONSTANT = "constant.workflowNode.create_data_node_content";

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowNodeCreateSettings.class);
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasFormModel paasFormModel;

    @Override
    public Integer type() {
        return WorkflowNodeTypeEnum.CREATE_NODE.getType();
    }

    @Override
    public WorkflowNodeTreePojo getContent(WorkflowNodeEntity workflowNodeEntity, WorkflowGetPojo workflowGetPojo) throws XbbException {

        WorkflowNodeTreePojo workflowNodeTreePojo = new WorkflowNodeTreePojo();
        try {
            List<String> list = getNodeContent(workflowGetPojo, workflowNodeEntity, CONSTANT);
            workflowNodeTreePojo.setContent(list);
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeCreateSettings.getContent error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return workflowNodeTreePojo;
    }

    @Override
    public WorkflowNodeGetVO get(WorkflowNodeEntity workflowNodeEntity) throws XbbException {
        try {
            String corpid = workflowNodeEntity.getCorpid();
            InsertRecordNode insertRecordNode = JSON.parseObject(workflowNodeEntity.getConfigData(), InsertRecordNode.class);
            NodeCoreConfigurationPojo nodeCoreConfigurationPojo = new NodeCoreConfigurationPojo();
            InsertRecordNodeVO insertRecordNodeVO = getInsertRecordNode(workflowNodeEntity, insertRecordNode, corpid);
            // 获取表单名称
            String formName = getFormName(workflowNodeEntity, corpid);
            nodeCoreConfigurationPojo.setInsertRecordNode(insertRecordNodeVO);
            return new WorkflowNodeGetVO(formName, workflowNodeEntity.getAppId(), workflowNodeEntity.getFormId(), workflowNodeEntity.getMenuId(), workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(),
                    workflowNodeEntity.getUid(), workflowNodeEntity.getId(), workflowNodeEntity.getPrevId(), workflowNodeEntity.getWrapperId(), nodeCoreConfigurationPojo);
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeCreateSettings.get error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private InsertRecordNodeVO getInsertRecordNode(WorkflowNodeEntity workflowNodeEntity, InsertRecordNode insertRecordNode, String corpid) throws XbbException {

        if (Objects.isNull(insertRecordNode) || Objects.isNull(insertRecordNode.getOperations())) {
            return null;
        }
        Set<Long> workflowNodeIdSet = new HashSet<>();
        Set<Long> formIdSet = new HashSet<>();
        Set<Long> workOrderFormIdSet = new HashSet<>();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), workflowNodeEntity.getBusinessType())) {
            workOrderFormIdSet.add(workflowNodeEntity.getFormId());
        } else {
            formIdSet.add(workflowNodeEntity.getFormId());
        }
        if (Objects.equals(BasicConstant.TWO, insertRecordNode.getChooseDataSource())) {
            Long workflowNodeId = insertRecordNode.getWorkflowNodeId();
            workflowNodeIdSet.add(workflowNodeId);
            Long formId = insertRecordNode.getDataSourceFormId();
            Integer businessType = insertRecordNode.getDataSourceBusinessType();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                workOrderFormIdSet.add(formId);
            } else {
                formIdSet.add(formId);
            }
        }
        // 获取表单id，节点id
        getFormIdSet(insertRecordNode.getOperations(), formIdSet, workOrderFormIdSet, workflowNodeIdSet);
        // 获取节点信息
        Map<Long, WorkflowNodeEntity> workflowNodeEntityMap = getWorkflowNodeMap(workflowNodeIdSet, corpid);
        String nodeName = "";
        boolean hasKey = workflowNodeEntityMap.containsKey(insertRecordNode.getWorkflowNodeId());
        Integer delete = hasKey ? 1 : 0;
        String formName = "";
        if (Objects.equals(BasicConstant.TWO, insertRecordNode.getChooseDataSource()) && hasKey) {
            nodeName = workflowNodeEntityMap.get(insertRecordNode.getWorkflowNodeId()).getName();
            Long formId = insertRecordNode.getDataSourceFormId();
            Integer businessType = insertRecordNode.getDataSourceBusinessType();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKey(formId, corpid);
                if (Objects.nonNull(workOrderFormEntity)) {
                    formName = workOrderFormEntity.getName();
                }
            } else {
                PaasFormEntity paasFormEntity = paasFormModel.getByKey(formId, corpid);
                if (Objects.nonNull(paasFormEntity)) {
                    formName = paasFormEntity.getName();
                }
            }
        }



        Map<Long, Map<String, FieldAttrEntity>> explainMap = proFormHelp.getFormFieldMap(formIdSet, corpid);
        Map<Long, Map<String, FieldAttrEntity>> workOrderExplainMap = proFormHelp.getWorkOrderFormFieldMap(workOrderFormIdSet, corpid);
        List<WorkflowOperationsVO> operations = getReturnOperationList(insertRecordNode.getOperations(), workflowNodeEntity.getFormId(), workflowNodeEntity.getBusinessType(), explainMap, workOrderExplainMap, workflowNodeEntityMap);
        InsertRecordNodeVO insertRecordNodeVO = new InsertRecordNodeVO(insertRecordNode.getEditedData(), delete, insertRecordNode.getChooseDataSource(), insertRecordNode.getWorkflowNodeId(), insertRecordNode.getDataSourceFormId(),
                insertRecordNode.getDataSourceSaasMark(), insertRecordNode.getDataSourceBusinessType(), nodeName, formName, operations);

        return insertRecordNodeVO;
    }

    @Override
    public WorkflowEnableVO check(WorkflowNodeEntity workflowNodeEntity, Map<Long, WorkflowNodeEntity> nodeMap, WorkflowGetPojo workflowGetPojo) throws XbbException {
        WorkflowEnableVO workflowEnableVO = new WorkflowEnableVO();
        try {
            InsertRecordNode insertRecordNode = JSON.parseObject(workflowNodeEntity.getConfigData(), InsertRecordNode.class);
            if (Objects.equals(workflowNodeEntity.getTriggerType(), WorkflowTriggerMethodEnum.FORM.getType())) {
                if (CollectionUtils.isEmpty(insertRecordNode.getOperations())) {
                    workflowEnableVO.setSuccess(0);
                    workflowEnableVO.setWorkflowNodeId(workflowNodeEntity.getId());
                } else {
                    validateOperate(workflowNodeEntity, nodeMap, insertRecordNode.getOperations(), workflowGetPojo);
                }
            }
        } catch (XbbException e) {
            workflowEnableVO.setSuccess(0);
            workflowEnableVO.setWorkflowNodeId(workflowNodeEntity.getId());
            workflowEnableVO.setMessage(e.getMsg());
        }

        return workflowEnableVO;
    }

    @Override
    public void replaceWorkflowNodeId(WorkflowNodeEntityExt workflowNodeEntityExt, Map<Long, Long> workflowNodeMap) throws XbbException {
        InsertRecordNode insertRecordNode = JSON.parseObject(workflowNodeEntityExt.getConfigData(), InsertRecordNode.class);
        if (Objects.nonNull(insertRecordNode)) {
            if (Objects.nonNull(insertRecordNode.getWorkflowNodeId())) {
                insertRecordNode.setWorkflowNodeId(workflowNodeMap.get(insertRecordNode.getWorkflowNodeId()));
            }
            if (CollectionUtils.isNotEmpty(insertRecordNode.getOperations())) {
                WorkflowNodeUtil.replaceWorkflowNodeId(insertRecordNode.getOperations(), workflowNodeMap);
                workflowNodeEntityExt.setConfigData(JSON.toJSONString(insertRecordNode));
            }
        }
    }
}

